package dao

import (
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"newapp/model"
)

func DaoUser(db *gorm.DB, phone string) bool {
	var user model.User
	db.Where("phone=?", user.Phone).First(&user)
	if user.ID != 0 {
		return true
	}
	return false
}

func CreateUserDao(db *gorm.DB, user model.User) error {
	hassPassword, err := bcrypt.GenerateFromPassword([]byte(user.PassWord), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	newUser := model.User{
		UserName: user.UserName,
		PassWord: string(hassPassword),
		Phone:    user.Phone,
	}
	db.Create(&newUser)
	return nil
}

func IsCorrectDao(db *gorm.DB, user model.User) bool {
	var newUser model.User
	db.Where("user_name=?", user.UserName).First(&newUser)
	if newUser.ID != 0 {
		if err := bcrypt.CompareHashAndPassword([]byte(newUser.PassWord), []byte(user.PassWord)); err != nil {
			return false
		} else {
			return true
		}
	} else {
		return false
	}

}
